package com.aabte.lota.auth.auth.shiro;

import com.aabte.lota.auth.account.entity.User;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/4/5
 */
@Data
public class UsernamePasswordCredentialsMatcher implements CredentialsMatcher {

  private int hashIterations = 1;

  @Override
  public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
    UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
    SimpleAuthenticationInfo simpleAuthenticationInfo = (SimpleAuthenticationInfo) info;

    User user = (User) simpleAuthenticationInfo.getPrincipals().getPrimaryPrincipal();
    String cipherTextFromDb = user.getPassword();

    String salt = user.getSalt();
    String plainText = String.valueOf(usernamePasswordToken.getPassword());
    String cipherText = PasswordUtils.encryptPassword(plainText, salt, hashIterations);

    return StringUtils.equals(cipherTextFromDb, cipherText);
  }
}
